import { View } from "@tarojs/components";
import { ReactNode } from "react";
import Taro from "@tarojs/taro";

import ByText from "./ByText";
import BySpace from "./BySpace";
import ByImage from "./ByImage";
import BySquare from "./BySquare";

import { ensureCompleteUrl } from "@/utils";

type ByImageGroupProps = {
  urls?: string[];
  limit?: number;

  size?: string | number;
  preview?: boolean;

  // 是否显示长按菜单
  showmenu?: boolean;
  showDelete?: boolean;
  showEmptyTip?: boolean;

  // 把modelValue格式化为 string[]格式数据
  formatUrls?: (e: any) => any[];

  // 把string
  deformatUrls?: (e: string[]) => any;

  slotFooter?: ReactNode;
};

type ByImageGroupEvent = {
  /**
   * 自定义删除逻辑
   * @param index
   * @param url
   * @returns
   */
  onDelete?: (index: number, url: string) => void | Promise<any>;
  /**
   * 删除后更新数据urls
   * @param event
   * @returns
   */
  onChange?: (event: string[], deleteIndex: number) => void;
};

export default ({
  urls,
  size,
  preview,
  showmenu,
  showDelete,
  showEmptyTip,
  slotFooter,
  limit,

  onDelete,
  onChange,
}: ByImageGroupProps & ByImageGroupEvent) => {
  // 删除处理
  const handleDelete = async (index: number, url: string) => {
    await onDelete?.(index, url);

    if (!onDelete) {
      const { cancel } = await Taro.showModal({ title: "确定删除该文件？" });
      if (cancel) return;
    }

    urls!.splice(index, 1);
    onChange?.([...urls!], index);
  };

  urls = urls || [];

  const showPlaceholer = showEmptyTip && (!urls || urls.length == 0);

  // 补全后图片列表
  const newUrls = urls.map(ensureCompleteUrl);
  // 仅渲染的图片列表
  const list = newUrls.slice(0, limit || urls.length);

  // 剩余未显示数量
  const remaining = urls.length - list.length;

  const previewImage = () => {
    Taro.previewImage({
      current: newUrls[limit! + 1],
      urls: newUrls,
    });
  };

  return (
    <View>
      {showPlaceholer && (
        <View className="text-xs text-third mb-3">无图片数据</View>
      )}

      <BySpace>
        {list?.map((url, index) => (
          <ByImage
            key={index}
            src={url}
            size={size}
            urls={newUrls}
            preview={preview}
            showmenu={showmenu}
            showDelete={showDelete}
            circle={false}
            onDelete={() => handleDelete(index, url)}
          />
        ))}

        {remaining > 0 && (
          <BySquare
            size={size}
            className="bg-page"
            circle={false}
            onClick={previewImage}
          >
            <ByText type="third" size="sm">
              +{remaining}
            </ByText>
          </BySquare>
        )}

        {slotFooter}
      </BySpace>
    </View>
  );
};
